####################configuration####################
# sh refresh2enviroment.sh nanshan 119
NEED_CHECK_PROJECT_NAME=$1
environment=$2
PARENT_MAIN_PROJECT_PATH="${HOME}/zxh/project/yapai/${NEED_CHECK_PROJECT_NAME}"
MAIN_PROJECT_PATH=$(dirname `find ${PARENT_MAIN_PROJECT_PATH} -depth -name "src" | xargs ls -1d`)

DIR=$( dirname "$(readlink -f  ${BASH_SOURCE[0]})" )

name=`uname -s`
if [[ "${name}" = "Linux" ]]; then
currentHome=$( dirname "$(readlink -f  ${BASH_SOURCE[0]})" )
else
currentHome=$( dirname "$(greadlink -f  ${BASH_SOURCE[0]})" )
fi
YAPAI_HOME=$(dirname "$currentHome")
IP=(`cat ${YAPAI_HOME}/enviroment/${environment} | jq -r '.ip'`)
DATABASE_USER_NAME=(`cat ${YAPAI_HOME}/enviroment/${environment} | jq -r '.database_user_name'`)
DATABASE_PASSWORD=(`cat ${YAPAI_HOME}/enviroment/${environment} | jq -r '.database_password'`)
DATABASE_PORT=(`cat ${YAPAI_HOME}/enviroment/${environment} | jq -r '.database_port'`)

BASE_FILE_SQL=(${NEED_CHECK_PROJECT_NAME})
for bfs in ${BASE_FILE_SQL[@]}
do
  DATABASE_NAME=${NEED_CHECK_PROJECT_NAME}
  files=(`find ${MAIN_PROJECT_PATH}/src/main/resources/sql/update -type f | xargs ls -1d | sort -r`)
  for (( i=${#files[@]};i>0;i--))
  do
    import_file=${files[i-1]}
    echo -e "\033[32m ${import_file} \033[0m"
    IMPORT_RESULT=`mysql -f -h${IP} -u${DATABASE_USER_NAME} -p${DATABASE_PASSWORD} -P${DATABASE_PORT} -D${DATABASE_NAME} < ${import_file} 2>&1 | sed -n '2,$p'`
    echo ${IMPORT_RESULT}
    errors_regex=`ls -1 ${DIR}/error`
    for regex in ${errors_regex[@]}
    do
    # echo "${IMPORT_RESULT}"
      # REG='ERROR\s+1064.*:(.*)'
      REG=`cat ${DIR}/error/${regex} | sed -n '1p'`
      if [[ "${IMPORT_RESULT}" =~ ${REG} ]]
      then
        echo -e "----------------------------------\033[32m errors \033[0m----------------------------------"
        echo -e "\033[31m ${BASH_REMATCH[1]} \033[0m"
        echo -e "----------------------------------\033[32m errors \033[0m----------------------------------"
        mysql -h${DATABASE_HOST} -u${DATABASE_USERNAME} -p${DATABASE_PASSWORD} -e 'drop database '"${DATABASE_NAME}"''
        exit
      fi
    done
  done
done
